package com.teach;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

public class PropertiesTest2 {

	public static void main(String[] args) {
		Properties p = new Properties();// Map<String,String>
		// 设置属性
		p.setProperty("name", "张三");
		p.setProperty("name11", "value11");
		System.out.println(p);
		
		//从文件中装载配置文件
		try {
			InputStream in = new FileInputStream(new File("d:\\upload\\a.txt"));
			p.load(in);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("配置文件未找到");
		}catch (IOException e) {
			e.printStackTrace();
			System.out.println("读取配置文件失败");
		}
		System.out.println(p);
		

		try {
			Reader reader = new FileReader(new File("d:/upload/a.txt"));
			p.load(reader);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("配置文件未找到");
		}catch (IOException e) {
			e.printStackTrace();
			System.out.println("读取配置文件失败");
		}
		System.out.println(p);
		

		try {
			InputStream in = new FileInputStream(new File("d:\\upload\\a.txt"));
			Reader reader = new InputStreamReader(in, "GBK");
			p.load(reader);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("配置文件未找到");
		}catch (IOException e) {
			e.printStackTrace();
			System.out.println("读取配置文件失败");
		}
		System.out.println(p);
		
		//配置文件的保存
		try {
			OutputStream out = new FileOutputStream(new File("d:/upload/1-"+UUID.randomUUID().toString()+".txt"));
			p.store(out, "注释说明");
			
			Writer writer = new FileWriter(new File("d:/upload/2-"+UUID.randomUUID().toString()+".properties"));
			p.store(writer,"readme注释说明");
			
			out = new FileOutputStream(new File("d:/upload/3-"+UUID.randomUUID().toString()+".xml"));
			p.storeToXML(out, "注释","UTF-8");
		}catch (Exception e) {
			e.printStackTrace();
			System.out.println("保存配置文件失败");
		}
		
		
		//从classpath中读取配置文件
		p = new Properties();
		try {
			p.load(PropertiesTest2.class.getResourceAsStream("config.properties"));
//			p.load(PropertiesTest2.class.getResourceAsStream("./config.properties"));
			System.out.println(p);

//			p.load(PropertiesTest2.class.getResourceAsStream("../../config.properties"));
			p.load(PropertiesTest2.class.getResourceAsStream("/config.properties"));
			System.out.println(p);
			
		}catch (Exception e) {
			e.printStackTrace();
			System.out.println("读取配置文件失败");
		}
	}
}
